package com.rzhd.coursepatriarch.common.api.common;


import android.util.Log;

import com.rzhd.coursepatriarch.common.base.BaseApplication;
import com.rzhd.coursepatriarch.common.constants.HttpConstants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * @author yql
 * Time: 2018/6/10.
 */
public class RetrofitFactory {

    private static RetrofitFactory mRetrofitFactory;
    private Retrofit mRetrofit;

    public static RetrofitFactory getInstance() {
        if (mRetrofitFactory == null) {
            synchronized (RetrofitFactory.class) {
                if (mRetrofitFactory == null) {
                    mRetrofitFactory = new RetrofitFactory();
                }
            }
        }
        return mRetrofitFactory;
    }

    public RetrofitFactory() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //设置超时连接
                .connectTimeout(HttpConstants.TIME_OUT, TimeUnit.SECONDS)
                //设置写入超时时间
                .writeTimeout(HttpConstants.TIME_OUT, TimeUnit.SECONDS)
                //设置读取超时时间
                .readTimeout(HttpConstants.TIME_OUT, TimeUnit.SECONDS)
                //添加其他拦截器
                .addInterceptor(InterceptorUtil.getHeaderInterceptor())
                //添加日志拦截器
                .addInterceptor(InterceptorUtil.getLogInterceptor())
                //添加请求拦截器
                .addInterceptor( CusstomInterceptor.getInstance(BaseApplication.getInstance().getApplicationContext()))
                //设置缓存文件
                .cache(InterceptorUtil.getCache())
                .build();

        mRetrofit = new Retrofit.Builder()
                //传入base url
                .baseUrl(HttpConstants.BASE_URL)
                //添加String转换器
                .addConverterFactory(StringConverterFactory.create())
                //添加Gson转换器
//                .addConverterFactory(GsonConverterFactory.create())
                //添加rxjava转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //传入创建的okHttpclient
                .client(okHttpClient)
                .build();
    }


    public Retrofit getRetrofit() {
        return mRetrofit;
    }
}
